// 登录相关API
import { post, get } from '../../common/httptools';
import { urlconstant } from '../../constant/index';
import { setUserInfo, setToken, clearUserInfo } from '../../common/tools';

// 登录
export const login = async (data) => {
  try {
    const res = await post(urlconstant.LOGON.LOGIN, data);
    
    if (res.success && res.data) {
      // 存储用户信息和token
      setUserInfo(res.data.userInfo);
      setToken(res.data.token);
    }
    
    return res;
  } catch (error) {
    console.error('登录失败', error);
    throw error;
  }
};

// 注册
export const register = async (data) => {
  try {
    const res = await post(urlconstant.LOGON.REGISTER, data);
    
    if (res.success && res.data) {
      // 注册成功后自动登录
      setUserInfo(res.data.userInfo);
      setToken(res.data.token);
    }
    
    return res;
  } catch (error) {
    console.error('注册失败', error);
    throw error;
  }
};

// 获取用户信息
export const getUserInfo = async () => {
  try {
    const res = await get(urlconstant.LOGON.GET_USER_INFO);
    return res;
  } catch (error) {
    console.error('获取用户信息失败', error);
    throw error;
  }
};

// 退出登录
export const logout = () => {
  try {
    clearUserInfo();
    return { success: true, message: '退出成功' };
  } catch (error) {
    console.error('退出登录失败', error);
    throw error;
  }
};

// 检查登录状态
export const checkLoginStatus = async () => {
  try {
    const res = await getUserInfo();
    return res.success;
  } catch (error) {
    // 如果请求失败，说明登录状态已失效
    clearUserInfo();
    return false;
  }
};

export default {
  login,
  register,
  getUserInfo,
  logout,
  checkLoginStatus
};